<template>
  <div class="user-list-container">

    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-card class="search-card">
        <el-form :model="searchForm" :inline="true" class="search-form">
          <el-form-item label="工号">
            <el-input v-model="searchForm.workNo" placeholder="请输入工号" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="searchForm.realName" placeholder="请输入姓名" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="职位">
            <el-select v-model="searchForm.positionCode" placeholder="请选择职位" clearable style="width: 200px">
              <el-option v-for="position in positionOptions" :key="position.positionCode"
                         :label="position.positionName" :value="position.positionCode" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :icon="Search">
              搜索
            </el-button>
            <el-button @click="handleReset" :icon="Refresh">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-section">
      <el-button type="primary" @click="handleAdd" :icon="Plus">
        新增员工
      </el-button>
      <el-button @click="handleExport" :icon="Download">
        导出数据
      </el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-card>
        <el-table :data="tableData" v-loading="loading" @selection-change="handleSelectionChange" stripe border
                  style="width: 100%">
          <!-- <el-table-column type="selection" width="55" /> -->
          <!-- <el-table-column prop="staffId" label="ID" width="80" /> -->
          <el-table-column prop="workNo" label="工号" width="120" />
          <el-table-column prop="realName" label="姓名" width="100" />
          <el-table-column prop="positionName" label="职位" width="120">
            <!-- <template #default="{ row }">
                {{ getPositionName(row.positionCode) }}
            </template> -->
          </el-table-column>
          <el-table-column prop="deptName" label="部门" width="120">
            <!-- <template #default="{ row }">
                {{ getDepartmentNameByPosition(row.positionCode) }}
            </template> -->
          </el-table-column>
          <el-table-column prop="phone" label="联系电话" width="130" />
          <el-table-column prop="email" label="邮箱" width="180" />
          <el-table-column prop="status" label="状态" width="80">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="entryTime" label="入职时间" width="120" />
          <el-table-column prop="createTime" label="创建时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)" :icon="Edit">
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)" :icon="Delete">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                         :page-sizes="[5,10, 20, 50, 100,200]" :total="pagination.total"
                         layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                         @current-change="handleCurrentChange" />
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :before-close="handleDialogClose"><br>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工号" prop="workNo">
              <el-input v-model="formData.workNo" placeholder="请输入工号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="realName">
              <el-input v-model="formData.realName" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位" prop="positionCode">
              <el-select v-model="formData.positionCode" placeholder="请选择职位" style="width: 100%">
                <el-option v-for="position in positionOptions" :key="position.positionCode"
                           :label="position.positionName" :value="position.positionCode" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="在职" :value="1" />
                <el-option label="离职" :value="2" />
                <el-option label="休假" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职时间" prop="entryTime">
              <el-date-picker v-model="formData.entryTime" type="date" placeholder="请选择入职时间"
                              style="width: 100%" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleDialogClose">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                        确定
                    </el-button>
                </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Delete,
  Download,
  Edit
} from '@element-plus/icons-vue'
import hxxp from '@/utils/hxxp'
import axios from 'axios'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const selectedRows = ref([])

// 搜索表单
const searchForm = reactive({
  workNo: '',
  realName: '',
  positionCode: '',
})

// 表格数据
const tableData = ref([])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const formData = reactive({
  staffId: null,
  workNo: '',
  realName: '',
  positionCode: '',
  phone: '',
  email: '',
  status: 1,
  entryTime: '',

})

// 部门和职位选项数据
// const departmentOptions = ref([])
const positionOptions = ref([])

// 表单验证规则
const formRules = {
  workNo: [
    { required: true, message: '请输入工号', trigger: 'blur' },
    { min: 3, max: 20, message: '工号长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  positionCode: [
    { required: true, message: '请选择职位', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  entryTime: [
    { required: true, message: '请选择入职时间', trigger: 'change' }
  ]
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    1: 'success',
    2: 'danger',
    3: 'warning'
  }
  return statusMap[status] || 'info'
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}



// 获取职位列表
const getPositionList = async () => {
  try {
    const response = await hxxp.get('/aiPosition/list')
    if (response.code === 100200) {
      positionOptions.value = response.data || []
    }
  } catch (error) {
    console.error('获取职位列表失败:', error)
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '在职',
    2: '离职',
    3: '休假'
  }
  return statusMap[status] || '未知'
}

// 获取用户列表
const getUserList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    }

    // 这里需要根据实际后端API调整
    const response = await hxxp.get('/aiStaffUser/list', { params })
    console.log(response);


    if (response.code === 100200) {
      tableData.value = response.data.list
      pagination.total = response.data.total || 0
      pagination.currentPage = response.data.pageNum || 1
      pagination.pageSize = response.data.pageSize || 5
    } else {
      ElMessage.error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getUserList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    if (typeof searchForm[key] === 'string') {
      searchForm[key] = ''
    } else {
      searchForm[key] = null
    }
  })
  pagination.currentPage = 1
  getUserList()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增员工'
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑员工'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除员工 "${row.realName}" 吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const response = await hxxp.delete(`/aiStaffUser/${row.staffId}`)

    if (response.code === 100200) {
      ElMessage.success('删除成功')
      getUserList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}


// 导出数据
const handleExport = async () => {
  try {
    const params = {
      ...searchForm,
      pageNum: pagination.currentPage,
      pageSize:pagination.pageSize,
    }
    const response = await hxxp.get('/aiStaffUser/export', {
      params,
      responseType: 'blob'
    })

    // 创建下载链接
    const blob = new Blob([response], { type: 'application/vnd.ms-excel' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `员工信息_${new Date().toISOString().slice(0, 10)}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请稍后重试')
  }
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  getUserList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  getUserList()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    staffId: null,
    workNo: '',
    realName: '',
    positionCode: '',
    phone: '',
    email: '',
    status: 1,
    entryTime: ''
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    const isEdit = !!formData.staffId
    const url = isEdit ? `/aiStaffUser/${formData.staffId}` : '/aiStaffUser'
    const method = isEdit ? 'put' : 'post'

    const response = await hxxp[method](url, formData)

    if (response.code === 100200) {
      ElMessage.success(isEdit ? '更新成功' : '新增成功')
      dialogVisible.value = false
      getUserList()
    } else {
      ElMessage.error(response.message || (isEdit ? '更新失败' : '新增失败'))
    }
  } catch (error) {
    if (error !== false) { // 表单验证失败时 error 为 false
      console.error('提交失败:', error)
      ElMessage.error('操作失败，请稍后重试')
    }
  } finally {
    submitLoading.value = false
  }
}

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 组件挂载时获取数据
onMounted(() => {
  getUserList()
  //getDepartmentList()
  getPositionList()
})
</script>

<style scoped>
.user-list-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  opacity: 0.9;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin-bottom: 0;
}

.action-section {
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
}

.table-section {
  margin-bottom: 20px;
}

.table-section .el-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-list-container {
    padding: 10px;
  }

  .search-form {
    flex-direction: column;
  }

  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 12px;
  }

  .action-section {
    flex-direction: column;
  }

  .page-header h2 {
    font-size: 20px;
  }
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background: #f8f9fa;
  color: #495057;
  font-weight: 600;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background: #f8f9fa;
}

/* 按钮样式优化 */
.el-button {
  border-radius: 6px;
  font-weight: 500;
}

/* .el-button--primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
}

.el-button--primary:hover {
    background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
} */

/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #495057;
}

:deep(.el-input__inner) {
  border-radius: 6px;
}

:deep(.el-select .el-input__inner) {
  border-radius: 6px;
}

/* 对话框样式优化 */
:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
  padding: 20px;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

/* 标签样式优化 */
.el-tag {
  border-radius: 4px;
  font-weight: 500;
}

/* 分页样式优化 */
:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 6px;
  margin: 0 2px;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next) {
  border-radius: 6px;
}
</style>